import './App.scss'

// 导入子组件
import { CartHeader } from './components/CartHeader'
import { CartFooter } from './components/CartFooter'
import { GoodsItem } from './components/GoodsItem'
import axios from 'axios'
import { useState, useEffect } from 'react'

// axios根请求
const http = axios.create({
  baseURL: 'http://localhost:8888/',
})
export default function App() {
  // 主体单选数据状态
  const [goodsList, setGoodsList] = useState([])
  // 底部全选数据状态
  const [checkAll, setCheckAll] = useState(false)
  useEffect(() => {
    //请求列表数据
    const getGoodsList = async () => {
      const res = await http.get('/goodsList')
      // console.log(res)
      setGoodsList(res.data)
      setCheckAll(res.data.every((item) => item.goods_state))
    }
    getGoodsList()
  }, [])

  // 切换每个商品的选中状态
  const checkedChange = (id, cheack) => {
    // console.log(id, cheack)
    const newGoodsList = goodsList.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          goods_state: cheack,
        }
      }
      return item
    })
    // 更新本地数据
    setGoodsList(newGoodsList)
    // 发送更新请求
    http.patch(`/goodsList/${id}`, { goods_state: cheack })

    setCheckAll(newGoodsList.every((item) => item.goods_state))
  }

  // 改变全选状态
  const cheackAllChange = (checkAll) => {
    console.log(checkAll)
    setCheckAll(checkAll)

   // 修改本地选择状态
    setGoodsList(
      goodsList.map((item) => {
        return {
          ...item,
          goods_state: checkAll,
        }
      })
    )

    // // 发送请求更改全选状态
    goodsList.forEach((item) => {
      http.patch(`/goodsList/${item.id}`, {
        goods_state: checkAll,
      })
    })
  }

  // (选中)总件数
  const allCount = goodsList.reduce((prevCount, item) => {
    if (item.goods_state) {
      // 选中的计算总件数
      return prevCount + item.goods_count
    } else {
      return prevCount
    }
  }, 0)
  
  // (选中)总金额
  const allPrice = goodsList.reduce((prevPrice, item) => {
    if (item.goods_state) {
      return prevPrice + item.goods_price * item.goods_count
    } else {
      return prevPrice
    }
  },0)
  return (
    <div className="app">
      {/* 标题 */}
      <CartHeader>购物车案例</CartHeader>
      {/* 商品列表项 */}

      {goodsList.map((item) => {
        return (
          <GoodsItem key={item.id} {...item} checkedChange={checkedChange} />
        )
      })}

      {/* 底部 */}
      <CartFooter
        checkAll={checkAll}
        cheackAllChange={cheackAllChange}
        allCount={allCount}
        allPrice={allPrice}
      />
    </div>
  )
}
